import { extend, } from 'umi-request';
import { history } from 'umi';
import { message } from 'antd';
import { stringify } from 'querystring';

const loginPath = '/user/login';

const request = extend({
  // headers: {
  //   'Content-Type': 'application/json'
  // },
  method: 'POST',
  prefix: 'https://jxc-test.zjny.cc',
  errorHandler:
    (error) => {
      const { response } = error;
      if (response && response.status) {
        const { status, url } = response;
        message.error(`REQUEST ERROR: ${status}: ${url}`);
      }
      throw error;
    },
});

const loginOut = () => {
  const { query = {}, search, pathname } = history.location;
  const { redirect } = query;
  !redirect && history.replace({
    pathname: loginPath,
    search: stringify({
      redirect: pathname + search,
    }),
  });
};


const requestInterceptors = (url, options) => {

  if(options.url !== '/adminapi/loginByPwd' && options.url !== "/adminapi/upload"){
    options.params = {
      ...options.params,
      token: localStorage.getItem("userToken")
    }
  }
  
  return {
    url: url,
    options: {
      ...options,
    },
  };
};

const customMiddlewares = async (ctx, next: () => void) => {
  const { req } = ctx;

  if(!localStorage.getItem("userToken") && !localStorage.getItem("userId") && history.location.pathname !== loginPath){
    loginOut();
    return;
  }

  await next();

    // @ts-ignore
  if (req.options?.skipErrorHandler) {
    return;
  }
  if (!ctx.res.token && ctx.res.code !== 200) {
    message.error(`${ctx.res.msg}`).then(res => {
      localStorage.getItem("userToken") !== ctx.res.token && loginOut();
    });
    const error = new Error(ctx.res.msg);
    error.name = 'BizError';
    throw error;
  }
};


request.interceptors.request.use(requestInterceptors);
request.use(customMiddlewares);
export { request };
